using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Police : AbstractCharacter {
	
	private int _walkingDirection;
	private Rect _bounds;
	private GameEngine _engine;
	
	public void Setup(Rect r, GameEngine engine){
		r.x *= 0.6f;
		r.y *= 0.7f;
		r.width *= 0.6f;
		r.height *= 0.7f;
		_bounds = r;	
		_engine = engine;
	}
	
	protected void Awake(){
		_walkingDirection = 1;	
	}
	
	protected void FixedUpdate(){
		if(_engine.player.IsDead) return;
		
		Vector3 p = transform.position;
		Vector2 gp = _engine.GetGridPosition(p);
		Vector2 pp = _engine.GetGridPosition(_engine.player.transform.position);
		if(gp==pp){			
			Instantiate(_engine.prefabExplosion,transform.position,Quaternion.identity);
			_engine.player.Kill();
			return;
		}
		
		float vw = (_bounds.width*0.6f)*_walkingDirection;
		Vector2 gbp = _engine.GetGridPosition(p+new Vector3(vw,0,0));
		Block gb = _engine.GetBlockAt((int)gbp.x,(int)gbp.y);
		if(gb!=null){
			Block gb3 = _engine.GetBlockAt(gb.x,gb.y-1);
			if(gb==null || !gb.IsDestroyed || gb3==null || gb3.IsDestroyed) _walkingDirection = -_walkingDirection;
		}
		
		float vx = (speed*_walkingDirection)*Time.fixedDeltaTime;
		float vy = gravity*Time.fixedDeltaTime;
		
		Rect cb = _bounds;
		cb.x += p.x;
		cb.y += p.y;
		
		// check X collisions
		Rect nb = new Rect(_bounds.x,_bounds.y*0.5f,_bounds.width,_bounds.height*0.5f);
		nb.x += p.x+vx;
		nb.y += p.y;
		
		List<IQuadObject> collidersX = _engine.Search(nb);
		AbstractElement collideX = null;
		foreach(AbstractElement e in collidersX){
			if(e!=null && !e.IsDestroyed && !e.IsTrigger && UtilsRect.intersects(nb,e.worldBounds)){
				collideX = e;
				break;
			}
		}
		
		
		if(collideX!=null){
			float cx = collideX.transform.position.x;
			
			if(cx<p.x) vx += collideX.worldBounds.xMax-cb.xMin;
			else if(cx>p.x) vx += collideX.worldBounds.xMin-cb.xMax;
		} 
		
		p.x += vx;
		
		// check Y collisions
		nb = new Rect(_bounds.x*0.5f,_bounds.y,_bounds.width*0.5f,_bounds.height);
		nb.x += p.x;
		nb.y += p.y+vy;
		
		List<IQuadObject> collidersY = _engine.Search(nb);
		AbstractElement collideY = null;
		foreach(AbstractElement e in collidersY){
			if(e!=null && !e.IsTrigger && UtilsRect.intersects(nb,e.worldBounds)){
				Block b = e as Block;
				// give ladders priority
				bool bl = (b==null || !b.IsLadder);
				if(!e.IsDestroyed && bl){
					collideY = e;
					break;
				}
			}
		}
		
		if(collideY!=null) p.y = collideY.worldBounds.yMax+(_bounds.height*0.5f);
		else p.y += vy;
		
		// update position
		transform.position = p;
		transform.localScale = new Vector3(0.16f,0.16f,0.16f*_walkingDirection);
	}
	
}

